home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Windows News 2010 Summer - Disc 1
/
WN_Ete2010_CD1.iso
/
Onglet5
/
Weezo
/
Weezo setup.exe
/
{code_appDir}
/
www
/
ext
/
image.php
< prev
next >
Wrap
PHP Script
|
2010-05-19
|
18KB
|
464 lines
<?php
/**
* Display (and if requested resample) an image located out of document root
*
* parameters are passed with GET method :
* file : file name (including full path), url encoded
* (optional) w, h : width and height of image
*
* script should be called like : <img src="/ext/image.php?file=c%3foo.jpg&w=32&h=32"> or through cfExtImage function
*
* PHP version 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category NA
* @package NA
* @author Nicolas Bruley / Peer 2 World <contact@weezo.net>
* @copyright 2005-2009 Nicolas Bruley / Peer 2 World
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id:$
* @link http://www.weezo.net
* @since File available since Release 1.1.0
*/
/**
* @desc Generate and sent image and headers to ouptut
*
* @param string $completeFilename
* @param array $uri: parsed URI
*/
function imageGenerate($completeFilename,$uri){
// Image rotation
if(isset($uri['rot']) && is_numeric($uri['rot'])) $rotation=$uri['rot']; else $rotation=0;
// Resample quality (get resource-level values before closing session)
$resampleQuality=cfHGetVar('imageResampleQuality',DEFAULT_RESIZE_METHOD);
// JPG quality (get resource-level values before closing session)
$JPGQuality=cfHGetVar('thumbnailJPGQuality',DEFAULT_JPG_QUALITY);
// Stretch small images (get resource-level values before closing session)
$stretchSmallImages=cfRGetVar('stretchSmallImages');
//close session
$speedLimit=cfUGetVar('downloadSpeedLimit');
wSession_write_close(); unset($_SESSION);
set_time_limit(0);
// Headers
header('Keep-Alive: timeout=15, max=2000');
header('Proxy-Connection: Keep-Alive');
// No cache
if(isset($uri['cache']) && $uri['cache']=='0') WHeaders::noCache();
// Cache
else WHeaders::cache($completeFilename);
if(!isset($uri['w'])) $uri['w']=0; if(!isset($uri['h'])) $uri['h']=0;
require(INCLUDE_DIR.'mime_type.php');
/**
* File's icon
*/
if(isset($uri['icon'])){
header('Content-Type: image/png');
require_once(INCLUDE_DIR.'explorerFunctions.php');
// Extract icon from file
if(!($ico=efExtractIcon($completeFilename,false,((isset($uri['w']))?$uri['w']:16),array('icoPngCheck'=>1)))) {
require_once(INCLUDE_DIR.'outputFunctions.php');
$ico=file_get_contents(cfAppDocRoot().efIcon($completeFilename,false));
}
die($ico);
}
/**
* Audio files: extract cover
*/
if(substr(mimeType($completeFilename),0,5)=='audio')
imageExtractAudioCover($completeFilename,((isset($uri['w']))?$uri['w']:0),((isset($uri['h']))?$uri['h']:0),!isset($uri['noDC']));
/**
* Images
*/
if(substr(mimeType($completeFilename),0,5)=='image'){
// if resize requested, generate resized image and send it to output
if($rotation || $uri['w'] || $uri['h'] || (isset($uri['sq']) && $uri['sq'])){
header('Content-Type: image/jpeg');
if($uri['w'] || $uri['h'])
$res=cfCreateResizedJPG($completeFilename, 0, 0, 'return', $uri['w'], $uri['h'], $resampleQuality, $JPGQuality, $rotation, (isset($uri['sq']) && $uri['sq']), $stretchSmallImages);
else
$res=cfCreateResizedJPG($completeFilename, 0, 0, 'return', 0, 0, $resampleQuality, $JPGQuality, $rotation, (isset($uri['sq']) && $uri['sq']), $stretchSmallImages);
// Stream result to output
if($res) cfStreamString($res, $speedLimit);
}
//If no resize and no rotation requested, directly send image to output
else{
$ext=strtolower(substr($completeFilename,strrpos($completeFilename,'.')+1));
// browser supported extension : stream
if($ext=='jpg' || $ext=='gif' || $ext=='jpeg' || $ext=='png' || $ext=='itc' || $ext=='itc2') {
if($ext=='jpg' || $ext=='jpeg') header('Content-Type: image/jpeg');
if($ext=='png' || $ext=='itc' || $ext=='itc2') header('Content-Type: image/png');
if($ext=='gif') header('Content-Type: image/gif');
if($ext=='ico') header('Content-Type: image/x-icon');
// Stream file to output
if($ext=='itc')
cfStreamString(substr(file_get_contents($completeFilename),500),$speedLimit);
elseif($ext=='itc2')
cfStreamString(substr(file_get_contents($completeFilename),492),$speedLimit);
else
cfStreamFile($completeFilename,false,$speedLimit);
$res=true;
}
// unsupported: (try to) convert to jpg
else {
header('Content-Type:image/jpeg');
$res=cfCreateResizedJPG($completeFilename,0,0,"",0,0,$resampleQuality, $JPGQuality, 0,false, $stretchSmallImages);
// Stream result to output
if($res) cfStreamString($res,$speedLimit);
}
}
// If image couldn't be generated, return empty image
if(!$res) echo file_get_contents(cfAppDocRoot().'/gfx/dot.jpg');
// Update debug buffer
if(cfMGetVar('debugAsync')) cfDebugUpdateBuffer('DONE '.basename($completeFilename).' '.(($uri['w'] || $uri['h'])?' resampled:'.$uri['w'].'x'.$uri['h']:''));
exit;
}
/**
* Other files
*/
@unlink(cfAppDataDir().'/thumbnail.tmp.jpg');
// Generate resized image with createJPG
if(!cfGGetVar('disableCreateJPG') && cfStreamProc('"'.cfAppBinDir().'/createJPG.exe" "'.$completeFilename.'" "'.cfAppDataDir().'/thumbnail.tmp.jpg" '.(($uri['w'])?$uri['w']:'160').' '.(($uri['h'])?$uri['h']:'120').' all no 100 '.$JPGQuality,array('stdout'=>'return'))!='NOK'
&& file_exists(cfAppDataDir().'/thumbnail.tmp.jpg')){
header('Content-Type: image/jpeg');
echo file_get_contents(cfAppDataDir().'/thumbnail.tmp.jpg');
@unlink(cfAppDataDir().'/thumbnail.tmp.jpg');
}
else{
header('Content-Type: image/jpeg');
imagejpeg(imagecreatetruecolor((($uri['w'])?$uri['w']:'160'),(($uri['h'])?$uri['h']:'120')));
}
}
/**
* @desc Check published image access rights and send to output
*
* @param array $uri: parsed URI
*/
function imagePublished($uri){
$id=$uri['dlToken'];
require_once(INCLUDE_DIR.'explorerFunctions.php');
$tokenList=efTokensRead();
if(!isset($tokenList[$id]) || $tokenList[$id]['type']!=='publishImage') logError('invalid published video id ('.$id.')');
$token=$tokenList[$id];
// Check file's existence
if(!is_file($token['filename'])) logError('perempted published image ('.$token['filename'].')');
// Increase number of downloads and save
$tokenList[$id]['limitNb']--;
efTokensWrite($tokenList);
// Full-size image
if(isset($uri['w']) && isset($uri['h']) && $uri['w']==0 && $uri['h']==0 && @$token['fullsizeAllowed']) imageGenerate($token['filename'],array('w'=>0,'h'=>0));
// Resized image
imageGenerate($token['filename'],array('w'=>$token['w'],'h'=>$token['h']));
}
/**
* @desc Send a resized version of an image located into /gfx dir or subdir
*
* @param array $uri: parsed URI
*/
function imageResizedGFX($uri){
// Check if browser is requesting a cached image, and if so, just return not-modified-file header
checkCache();
$completeFilename=$uri['file'];
$completeFilename=cfAppDocRoot().str_replace('..','',$completeFilename);
if(!is_file($completeFilename)) logError('extImage: NX '.$completeFilename.' doesnt exist');
header('Last-Modified: '.gmdate("D, d M Y H:i:s",@filemtime($completeFilename)).' GMT');
header('Etag: "'.md5($_SERVER['REQUEST_URI']).'"');
header('Content-Type:image/jpeg');
cfCreateResizedJPG($completeFilename, 0, 0, '', $uri['w'], $uri['h'], 2, 75, 0, false, true);
exit;
}
/**
* @desc Generate an image with error message, and log error
*
* @param string $logCaption : error message
*/
function logError($logCaption){
global $uri;
cfLog($logCaption, LOG_ER);
cfDebugUpdateBuffer('ERROR: '.$logCaption);
$winDir=isset($_SERVER['SystemRoot'])?str_replace('\\','/',$_SERVER['SystemRoot']):'c:/windows';
// Send headers with no-cache
WHeaders::noCache();
WHeaders::contentType("Content-type: image/png");
$capt=str_replace('extImage: ','',$logCaption);
$capt=substr($capt,0,floor(strlen($capt)/3))."\n".substr($capt,floor(strlen($capt)/3),floor(strlen($capt)/3))."\n".substr($capt,-floor(strlen($capt)/3));
// Generate black image with a ? watermark
$w=(isset($uri['w']) && $uri['w'])?$uri['w']:(int)(5*strlen($capt)/3);
$h=(isset($uri['h']) && $uri['h'])?$uri['h']:(int)(5*strlen($capt)/3);
$im = imagecreatetruecolor($w, $h);
imagefilledrectangle($im, 0, 0, $w, $h, imagecolorallocate($im, 0, 0, 0));
$tw=floor(3*min($w,$h)/4);
$th=$tw; $tw*=0.75;
$se = imagecreatetruecolor($tw,$th);
imagettftext($se, $th, 0, $tw*0/16, $th, imagecolorallocate($im, 45, 45, 45), $winDir.'/fonts/arial.ttf', '?');
imagecopy($im,$se,floor(($w-$tw)/2),floor(($h-$th)/2),0,0,$tw,$th);
imagepng($im);
imagedestroy($im);
exit;
}
/**
* @desc return not-modified-file header
*
*/
function return304(){
header('HTTP/1.x 304 Not Modified');
header('X-Powered-By:');
header("Date: " . gmdate("D, d M Y H:i:s") . " GMT");
header('Etag: "'.md5($_SERVER['REQUEST_URI']).'"');
header('Content-Length');
header('Content-Type');
exit;
}
/**
* @desc Check if browser is requesting a cached image, and if so, just return not-modified-file header
*
* @param string $completeFilename: filename including path
*/
function checkCache($completeFilename=false){
global $uri;
if(isset($uri['cache']) && $uri['cache']=='0') return false;
$headers=getallheaders();
if(!isset($headers['If-Modified-Since']) && !isset($headers['If-None-Match'])) return false;
if(isset($headers['If-None-Match']) && $headers['If-None-Match']!='"'.md5($_SERVER['REQUEST_URI']).'"') return false;
if(isset($headers['If-Modified-Since']) && $completeFilename){
if(!($date=strtotime($headers['If-Modified-Since']))) return304();
if($date<@filemtime($completeFilename)) return false;
}
return304();
}
/**
* @desc Extract and send audio file's cover to output
*
* @param string $completeFilename
* @param integer $width: ouput width
* @param integer $height: ouput height
* @param bool $directoryCover: false not to use directory cover if no embeded cover found
*/
function imageExtractAudioCover(&$completeFilename,$width=0,$height=0,$directoryCover=true){
$ext=cfFileExtension($completeFilename);
/**
* MP3 ID3 image
*/
if($ext=='mp3'){
require(INCLUDE_DIR.'miscFunctions.php');
$cover=new id3V2Ext($completeFilename);
// ID3 embeded image: generate and send to output
if($cover->hasImage()) $cover->generate($width,$height);
}
/**
* WMA embedded image
*/
elseif($ext=='wma' || $ext=='wmv' || $ext=='asf'){
// Get embedded image
require(INCLUDE_DIR.'php-reader/ASF.php');
$asf=@new ASF($completeFilename);
if(isset($asf->header->extendedContentDescription->descriptors['WM/Picture'])){
$v=$asf->header->extendedContentDescription->descriptors['WM/Picture'];
// Dirty parsing of WM/Picture data
$pos=0;
while($v[$pos]!='i' && $pos<50 && $pos<strlen($v)) $pos++;
if($v[$pos]=='i'){
$epos=$pos;
while(substr($v,$pos,2)!="\0\0" && $pos<50) $pos++;
$mimeType=str_replace("\0",'',substr($v,$epos,$pos-$epos));
while($v[$pos]=="\0" && $pos<strlen($v)) $pos++;
// Resized image
if($width && $height){
if($in=@imagecreatefromstring(substr($v,$pos))){
header('Content-Type: image/jpeg');
$out=imagecreatetruecolor($width,$height);
fastimagecopyresampled($out,$in,0,0,0,0,$width,$height,imagesx($in),imagesy($in),3);
imagejpeg($out,null,70);
imagedestroy($in);
imagedestroy($out);
exit;
}
}
// Original image
else{
header('Content-Type: '.$mimeType);
echo substr($v,$pos);
exit;
}
}
}
}
// ISO14496 format
elseif($ext=='3gp'||$ext=='3gpp'||$ext=='avc'||$ext=='dcf'||$ext=='m21'||$ext=='m4a'||$ext=='m4b'||$ext=='m4p'||$ext=='m4v'||$ext=='maf'||$ext=='mj2'||$ext=='mjp'||$ext=='mov'||$ext=='mp4'||$ext=='odf'||$ext=='sdv'||$ext=='qt'||$ext=='aac'){
require_once('ISO14496.php');
$isom=new ISO14496($completeFilename,array("base" => "moov.udta.meta.ilst"));
if (isset($isom->moov->udta->meta->ilst)) {
$ilst = $isom->moov->udta->meta->ilst;
if (isset($ilst->covr)) {
if($width && $height){
header('Content-type: image/jpeg');
if(($pos=strpos($ilst->covr,' ╪'))===false) // JPEG
$pos=strpos($ilst->covr,'ëPNG'); // PNG
if($pos!==false && ($in=imagecreatefromstring(substr($ilst->covr,$pos)))){
header('Content-Type: image/jpeg');
$out=imagecreatetruecolor($width,$height);
fastimagecopyresampled($out,$in,0,0,0,0,$width,$height,imagesx($in),imagesy($in),3);
imagejpeg($out,null,70);
imagedestroy($in);
imagedestroy($out);
exit;
}
}
else{
if ($ilst->covr->data->hasFlag(ISO14496_Box_DATA::JPEG))
header("Content-Type: image/jpeg");
elseif ($ilst->covr->data->hasFlag(ISO14496_Box_DATA::PNG))
header("Content-Type: image/png");
echo $ilst->covr->data->value;
}
}
}
}
// Else, look for best image in folder
if ($directoryCover){
require_once(INCLUDE_DIR.'explorerFunctions.php');
$completeFilename=efGetCoverFromFolder($completeFilename, $score);
}
else {
header('Content-type: image/jpeg');
cfCreateResizedJPG(cfAppDocRoot().'/gfx/cd.png',80,80,'',$width,$height);
exit;
}
}
// Decode and parse URI
$uri=cfParseExtURI();
// DEBUG
if(cfMGetVar('debugAsync')) cfDebugSetBuffer('image',$uri,'...');
// Published image
if(isset($uri['dlToken'])) imagePublished($uri);
// Simple resized gfx
if(isset($uri['file']) && substr($uri['file'],0,5)=='/gfx/') imageResizedGFX($uri);
/**
* Regular redirected images below this point
*/
wSession_start_nowrite();
header('P3P: policyref="/w3c/p3p.xml",CP="NON COR CURa OUR NOR NAV"');
// Verify that user logged in
if (!isset($_SESSION['userLogged'])) logError('extImage: UL '.$_SERVER['REQUEST_URI'].' unlogged access attempt');
// Set active resource
if(isset($uri['resId'])&& is_numeric($uri['resId']) && isset($_SESSION['res'][$uri['resId']]) && is_array($_SESSION['res'][$uri['resId']])) $_SESSION['activeResourceId']=$uri['resId'];
// Check that a file is passed
if(!isset($uri['file'])) logError('extImage: NI No passed image');
$completeFilename=$uri['file'];
// Shared list
if(cfSharedMode('list') && strpos($completeFilename,'*resourceDataDirBasePath*')===false) $completeFilename=cfSharedCompleteFilename($completeFilename);
// Shared folder
else{
// Don't debug-log images from resource data dir
if(strpos($completeFilename,'*resourceDataDirBasePath*')!==false) {
$_ENV['cfStreamFileNoLog']=1;
$completeFilename=str_replace('*resourceDataDirBasePath*',cfAppResourceDir(),$completeFilename);
}
else $completeFilename=str_replace('*resourceBasePath*',cfRGetVar('path'),$completeFilename);
}
// Check if browser is requesting a cached image, and if so, just return not-modified-file header
checkCache($completeFilename);
/**
* Check access rights
*/
// Resource specific file source and rights function : bypass common file's existence and access rights
// and (may) replace given file name by real file name
if(cfRGetVar('extAccessFunction')) {
$extAccessFunction = create_function('$completeFilename', cfRGetVar('extAccessFunction'));
if(!($completeFilename=$extAccessFunction($completeFilename))) logError('extImage: DA '.$_SERVER['REQUEST_URI'].' denied access');
}
// Administration, allow exe viewing
elseif (isset($uri['icon']) && cfUGetVar('administrator') && cfRGetVar('type')=='administration'){}
else{
// If file doesn't exist but is located into resource data directory and is an image and thumbnails allowed for this resource, generate
// (might happend if a problem occurs with createJPG)
if(!file_exists($completeFilename) && cfFileExtension($completeFilename)=='jpg' &&
cfIsSubDir(cfRGetVar('resourceDataDir'),$completeFilename) && cfRGetVar('resourceDataDirAccessAllowed') && cfRGetVar('path') &&
cfRGetVar('photoThumbnailsNeeded') && ($tmw=cfRGetVar('thumbnailMaxWidth')) &&
substr(basename($completeFilename),0,strlen($tmw))==$tmw){
$sourceCompleteFilename=cfJoinPathFile(cfRGetVar('path'),substr(dirname($completeFilename),strlen(cfRGetVar('resourceDataDir'))));
$sourceCompleteFilename.='/'.substr(cfFileWithoutExtension(basename($completeFilename)),strlen(cfRGetVar('thumbnailMaxWidth')));
// Verify that source file access is allowed
if(cfFileRights($sourceCompleteFilename,'download')){
// Everything is OK, thumbnail can be generated
cfCreateResizedJPG($sourceCompleteFilename,0,0,$completeFilename,cfRGetVar('thumbnailMaxWidth'),cfRGetVar('thumbnailMaxHeight'),false,false,0,cfRGetVar('cropThumbnails'));
}
}
if(!cfFileRights($completeFilename,'download')) logError('extImage: DA '.$completeFilename.' denied access');
//Verifies file's existence
if(!is_file($completeFilename)) logError('extImage: NX '.$completeFilename.' doesnt exist');
}
// Generate and sent image and headers to ouptut
imageGenerate($completeFilename,$uri)
?>